<template>
  <div class="app-container">
    <!-- <mainTilte title="商品管理" /> -->
    <form-selections :is-active="isActive" :items="formItems" :query-param.sync="queryParam" display="block" @handleSearch="handleSearch" />
    <div class="select_flex">
      <div class="operation_button_box">
        <el-button v-if="!isCompanyRole" v-action="'product@save'" size="small" type="success" icon="el-icon-circle-plus-outline" @click="addProductS">新增商品(内部)</el-button>
        <el-button v-else v-action="'product@save'" size="small" type="success" icon="el-icon-circle-plus-outline" @click="addProductC">新增商品(客户)</el-button>
        <el-button v-action="'product@batchExamine'" size="small" type="primary" @click="submitReview">提交审核</el-button>
        <el-button v-action="'product@examine'" size="small" type="primary" @click="productReview">商品审核</el-button>
        <el-button v-action="'product@productImport'" size="small" type="primary" @click="productImport">导入商品</el-button>
        <!-- <el-button type="danger">批量删除</el-button> -->
        <el-button v-action="'product@disable'" size="small" type="primary" @click="stopClick">禁用</el-button>
        <el-button v-action="'product@enable'" size="small" type="primary" @click="startClick">启用</el-button>
        <el-button v-action="'product@export'" size="small" :loading="exportLoading" type="primary" @click="handleExport">导出商品</el-button>
      </div>
      <div>
        <el-button size="small" type="primary" class="filter-item search mr5" icon="el-icon-search" @click="handleSearch">
          搜索
        </el-button>
        <more-search ref="moreSearch" v-model="queryParam" size="small" @search="handleSearch" />
        <el-button size="small" icon="el-icon-refresh" class="ml10" @click="handleRefresh">重置</el-button>
        <el-button size="small" @click="isActive=!isActive">{{ isActive?'展开':'收起' }}</el-button>
      </div>
    </div>

    <div v-loading="loading" class="page-grid">
      <egrid
        :screen-heigh="screenHeigh"
        class="egrid"
        stripe
        fit
        border
        highlight-current-row
        element-loading-text="正在努力加载中..."
        :column-type="['selection']"
        :data="tableData"
        :columns="columns"
        :columns-schema="columnsSchema"
        :columns-handler="columnsHandler"
        @selection-change="checkIds"
      />
      <epagination v-if="tableData" :total="total" :current="queryParam.page" :page-sizes="[50, 100, 200, 500]" layout="total, sizes, prev, pager, next, jumper" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange" />
    </div>
    <!-- 商品审核 -->
    <el-dialog
      v-if="dialogExamineVisible"
      v-loading.lock="loading"
      v-loading="loading"
      title=""
      :visible.sync="dialogExamineVisible"
      :close-on-click-modal="false"
      width="90%"
      class="dialogText header-none"
      element-loading-text="正在加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      center
    >
      <examineDetails :form="detailsData" />
      <el-form ref="examineForm" :model="examineForm" :rules="examineFormRule" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="">
              <el-radio-group v-model="examineForm.status">
                <el-radio :label="1">通过</el-radio>
                <el-radio :label="2">驳回</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="examineForm.status === 2" :span="16">
            <el-form-item label="驳回原因" prop="reason">
              <el-input v-model="examineForm.reason" type="textarea" autosize />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogExamineVisible = false">取消审核</el-button>
        <el-button type="primary" @click="saveExamineData()">确认审核</el-button>
      </span>
    </el-dialog>
    <!-- 导出 -->
    <down-modul url="/products/export" :search-param="queryParam" :form-visible-down.sync="formVisibleDown" :options-modul="downModulOptions" />
    <!-- 导入 -->
    <import-dialog url="/products/import" title="导入商品" :form-visible.sync="importDialogVisible" @download="downLoad" @handleRefresh="handleRefresh" />
    <updateBuyer title="编辑采购员" :buyers-id="buyersId" :form-visible.sync="formVisible" :ids="orderId" @handleSearch="handleSearch" />
  </div>
</template>

<script>
import list from '@/layout/mixin/list'
import thund from '@/components/base/thund'
import dicValues from '@/components/dicTransform/index'
import btnGroup from './components/btnGroup'
import updateBuyer from './components/updateBuyer.vue'
import examineDetails from './components/examineDetails'
import codeItem from '@/components/base/code'
import DownModul from '@/components/DownModul/index'
import { action } from '@/directive/permission/index.js' // 权限判断指令
import importDialog from '@/components/importDialog/index'
import { downloadStream } from '@/utils/index'
import { mapGetters } from 'vuex'
import moreSearch from './components/moreSearch'
import appText from '@/components/appText/index'
// import { downloadxlsx } from '@/utils/index'
import cacheList from '@/layout/mixin/cacheList'
export default {
  name: 'ProductManager',
  components: { moreSearch, examineDetails, DownModul, importDialog, updateBuyer },
  directives: {
    action
  },
  mixins: [list, cacheList],
  data() {
    const DICTIONARIES = {
      // 运营类型：1-代营 2-自营
      cooperationStatus: [
        {
          code: 1,
          name: '代营'
        },
        {
          code: 2,
          name: '自营'
        }
      ],
      // 包装方式 ：1-普通商品 2-多箱包装
      splitOrder: [
        {
          code: 1,
          name: '普通商品'
        },
        {
          code: 2,
          name: '多箱包装'
        }
      ],
      statusList: [
        // 审核状态 0-待提交 1-待采购员审核 2-待运营审核 3-运营审核通过     -1 采购员审核驳回 -2 运营员审核驳回
        {
          code: 0,
          name: '待审核'
        },
        {
          code: 1,
          name: '审核通过'
        },
        {
          code: 2,
          name: '审核驳回'
        },
        {
          code: 3,
          name: '待编辑'
        },
        {
          code: 4,
          name: '待提交'
        }
      ],
      // 状态 2-禁用 1-启用
      isableList: [
        {
          code: 1,
          name: '启用'
        },
        {
          code: 2,
          name: '禁用'
        }
      ]
    }
    return {
      otherHeight: 390,
      formVisible: false,
      orderId: '',
      buyersId: '',
      componentName: 'ProductManager',
      propsClassify: {
        disabled: 'disabled' // 商品分类只能选择二级
      },
      classifyList: [],
      allAmount: '',
      value: '',
      value1: [],
      loading: false,
      dialogAddVisible: false, // 新增供应商弹框
      title: '',
      loadingText: '',
      rule: {},
      searchClass: 1,
      isActive: false,
      formItems: [
        {
          label: '系统sku',
          key: 'code',
          type: 'input',
          placeholder: '请输入系统sku'
        },
        {
          label: '中文名',
          key: 'name_ch',
          type: 'input',
          placeholder: '请输入中文名'
        },
        {
          label: '商品类型',
          key: 'type',
          type: 'select',
          options: [
            {
              label: '内部商品',
              value: '0'
            },
            {
              label: '客户商品',
              value: '1'
            }
          ]
        },
        {
          label: '英文名',
          key: 'name_en',
          type: 'input',
          placeholder: '请输入英文名'
        },
        // {
        //   label: '所属供应商',
        //   key: 'supplier_name',
        //   type: 'input',
        //   placeholder: '请输入所属供应商'
        // },
        {
          label: '所属客户',
          key: 'company_name',
          type: 'input',
          placeholder: '请输入所属客户'
        },
        {
          label: '采购员',
          key: 'purchase_name',
          type: 'input',
          placeholder: '请输入采购员'
        },
        {
          label: '商品分类',
          key: 'category_ids',
          type: 'cascader',
          cLabel: 'lable',
          cValue: 'value',
          options: []
        },
        {
          label: 'oversize',
          key: 'oversize',
          type: 'select',
          options: [
            {
              label: '大于130inch',
              value: '1'
            },
            {
              label: '小于130inch',
              value: '2'
            }
          ]
        }
      ],
      // {
      //   name: '系统sku',
      //   code: 'code'
      // },
      // {
      //   name: '中文名',
      //   code: 'name_ch'
      // },
      // {
      //   name: '英文名',
      //   code: 'name_en'
      // },
      // {
      //   name: '所属供应商',
      //   code: 'supplier_name'
      // },
      // {
      //   name: '所属客户',
      //   code: 'company_name'
      // },
      // {
      //   name: '采购员',
      //   code: 'purchase_name'
      // }
      /** *
       * 定义搜索框
       */
      queryParam: {
        page: 1,
        limit: 50, // 默认是10
        totalRows: 0,
        type: '',
        value: '',
        category_id: '',
        is_disable: '', // 禁启用
        status: '', // 审核装填
        start_at: '', // 开始时间
        packing_method: '',
        operate_type: '',
        end_at: '' // 结束时间
      },
      /** *
       * 定义显示的表格
       */
      columns: [
        {
          label: '缩略图',
          prop: 'image_url',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '系统sku',
          prop: 'code',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '中文名称',
          prop: 'name_ch',
          width: '200',
          align: 'center',
          tooltip: false,
          component: codeItem,
          propsHandler({ row, col, column }) {
            return {
              code: row.name_ch ? row.name_ch : '',
              routePath: '/product/productManage/productDetails',
              queryData: { id: row.id }
            }
          }
        },
        {
          label: '类型',
          prop: 'type',
          width: '100',
          align: 'center',
          tooltip: false,
          component: appText,
          propsHandler({ row }) {
            return { text: row.type === 0 ? '内部' : '客户' }
          }
        },
        {
          label: '商品分类',
          prop: 'category_text',
          width: '160',
          align: 'center',
          tooltip: true
        },
        // {
        //   label: 'oversize',
        //   prop: 'oversize',
        //   width: '120',
        //   align: 'center',
        //   tooltip: false
        // },
        {
          label: '运营类型',
          prop: 'operate_type',
          width: '100',
          align: 'center',
          tooltip: false
        },
        {
          label: '包装方式',
          prop: 'packing_method',
          width: '200',
          align: 'center',
          tooltip: false
        },
        // {
        //   label: '产品条码UPC',
        //   prop: 'bar_code_upc',
        //   width: '200',
        //   align: 'center',
        //   tooltip: false
        // },
        // {
        //   label: '产品条码',
        //   prop: 'bar_code',
        //   width: '200',
        //   align: 'center',
        //   tooltip: false
        // },
        // {
        //   label: '计量单位',
        //   prop: 'unit',
        //   width: '100',
        //   align: 'center',
        //   tooltip: false
        // },
        // {
        //   label: '所属供应商',
        //   prop: 'supplier_name',
        //   width: '200',
        //   align: 'center',
        //   tooltip: false,
        //   component: appText,
        //   propsHandler({ row }) {
        //     return { text: row.supplier_name ? row.supplier_name : '' }
        //   }
        // },

        {
          label: '所属采购员',
          prop: 'purchase_name',
          width: '112',
          align: 'center',
          tooltip: false
        },
        {
          label: '所属客户',
          prop: 'company_name',
          width: '112',
          align: 'center',
          tooltip: false
        },
        {
          label: '审核状态',
          prop: 'status',
          width: '112',
          align: 'center',
          tooltip: false
        },
        {
          label: '审核原因',
          prop: 'reason',
          width: '200',
          align: 'center',
          component: appText,
          propsHandler({ row }) {
            return { text: row.reason }
          }
        },
        {
          label: '状态',
          prop: 'is_disable',
          width: '112',
          align: 'center',
          tooltip: false
        },
        {
          label: '创建人',
          prop: 'creator_name',
          width: '112',
          align: 'center',
          tooltip: false
        },
        {
          label: '创建时间',
          prop: 'created_at',
          width: '174',
          align: 'center',
          tooltip: false
        },
        {
          label: '修改人',
          prop: 'update_name',
          width: '112',
          align: 'center',
          tooltip: false
        },
        {
          label: '修改时间',
          prop: 'updated_at',
          width: '174',
          align: 'center',
          tooltip: false
        }
      ],
      /** *
       * 字典表组件
       */
      columnsSchema: {
        缩略图: {
          propsHandler({ col, row }) {
            return {
              img: row.image_url
            }
          },
          component: thund
        },
        包装方式: {
          propsHandler({ col, row }) {
            return {
              dictionaries: DICTIONARIES['splitOrder'],
              code: row[col.prop]
            }
          },
          component: dicValues
        },
        运营类型: {
          propsHandler({ col, row }) {
            return {
              dictionaries: DICTIONARIES['cooperationStatus'],
              code: row[col.prop]
            }
          },
          component: dicValues
        },
        审核状态: {
          propsHandler({ col, row }) {
            return {
              dictionaries: DICTIONARIES['statusList'],
              code: row[col.prop]
            }
          },
          component: dicValues
        },
        状态: {
          propsHandler({ col, row }) {
            return {
              dictionaries: DICTIONARIES['isableList'],
              code: row[col.prop]
            }
          },
          component: dicValues
        }
      },
      issignContract: [
        {
          name: '系统sku',
          code: 'code'
        },
        {
          name: '中文名',
          code: 'name_ch'
        },
        {
          name: '英文名',
          code: 'name_en'
        },
        // {
        //   name: '所属供应商',
        //   code: 'supplier_name'
        // },
        {
          name: '所属客户',
          code: 'company_name'
        },
        {
          name: '采购员',
          code: 'purchase_name'
        },
        {
          name: 'oversize',
          code: 'oversize'
        }
      ],
      form: {
        id: null,
        supplierCode: null, // 供应商代码
        supplierName: null, // 供应商名称
        settlementCycle: null, // 结算周期
        buyer: null, // 采购员
        contacts: '', // 联系人
        phone: null, // 联系人手机
        fixedTelephone: null, // 固定电话
        fax: null, // 传真
        // address: null, // 地址
        postcode: null, // 邮编
        payment: null, // 预付款比例
        notes: null // 备注说明
      },
      dialogExamineVisible: false,
      examineForm: {
        status: '',
        reason: ''
      },
      examineFormRule: {
        reason: [
          { required: true, message: '请输入驳回原因', trigger: 'blur' },
          { max: 500, message: '驳回原因必须是500个字符以内', trigger: 'blur' }
        ]
      },
      detailsData: {},

      formVisibleDown: false, // 导出弹窗 显示
      downModulOptions: [{
        'label': '商品SKU',
        'key': 'goods_code'
      },
      {
        'label': '产品图片',
        'key': 'image_url'
      },
      {
        'label': '中文名称*',
        'key': 'name_ch'
      },
      {
        'label': '英文名称',
        'key': 'name_en'
      },
      {
        'label': '商品分类*',
        'key': 'category_name_new'
      },
      {
        'label': '运营类型*',
        'key': 'operate_type_text'
      },
      // {
      //   'label': '所属供应商*',
      //   'key': 'supplie_name'
      // },
      {
        'label': '所属客户*',
        'key': 'company_name'
      },
      // {
      //   'label': '采购价（RMB)*',
      //   'key': 'purchase_price_rmb'
      // },
      // {
      //   'label': '采购价（USD)*',
      //   'key': 'purchase_price_usd'
      // },
      {
        'label': '产品尺寸',
        'key': 'size'
      },
      {
        'label': '产品重量',
        'key': 'weight'
      },
      {
        'label': '产品颜色',
        'key': 'color'
      },
      {
        'label': '产品材质',
        'key': 'material'
      },
      {
        'label': '配件',
        'key': 'parts'
      },
      {
        'label': '长（cm）*',
        'key': 'length'
      },
      {
        'label': '宽（cm）*',
        'key': 'width'
      },
      {
        'label': '高（cm）*',
        'key': 'height'
      },
      {
        'label': '毛重（kg）*',
        'key': 'weight_gross'
      },
      {
        'label': '净重（kg)',
        'key': 'weight'
      },
      {
        'label': '体积（m³）',
        'key': 'volume'
      },
      {
        'label': '长（inch）*',
        'key': 'length_AS'
      },
      {
        'label': '宽（inch）*',
        'key': 'width_AS'
      },
      {
        'label': '高（inch）*',
        'key': 'height_AS'
      },
      {
        'label': '毛重（lbs）*',
        'key': 'weight_gross_AS'
      },
      {
        'label': '净重（lbs)',
        'key': 'weight_AS'
      },
      {
        'label': 'Oversize参数',
        'key': 'oversize'
      },
      {
        'label': '箱率',
        'key': 'box_rate'
      },
      //   {
      //     'label': '长（cm）',
      //     'key': 'transport_length'
      //   },
      //   {
      //     'label': '宽（cm）',
      //     'key': 'transport_width'
      //   },
      //   {
      //     'label': '高（cm）',
      //     'key': 'transport_height'
      //   },
      {
        'label': '包装方式*',
        'key': 'packing_method_text'
      },
      {
        'label': '国内HS',
        'key': 'ZH_HS'
      },
      {
        'label': '国内退税率%',
        'key': 'tax_rebate_rate'
      },
      {
        'label': '国外HS',
        'key': 'EN_HS'
      },
      {
        'label': '国外关税税率%',
        'key': 'tax_tariff_rate'
      },
      {
        'label': '采购员*',
        'key': 'purchase_name'
      }], // 导出弹窗 options
      importDialogVisible: false,
      isCompanyRole: false,
      exportLoading: false,
      unitList: [], // 计量单位
      cachePaths: [
        '/product/productManage/addProductS',
        '/product/productManage/addProductC',
        '/product/productManage/productDetails'
      ]
    }
  },
  computed: {
    ...mapGetters(['roles'])
    // queryParamObj({ issignContract }) {
    //   const vm = this
    //   const item = issignContract.find((e) => e.code === vm.queryParam.type)
    //   const params = {}
    //   if (item) {
    //     params[item.code] = vm.queryParam.value
    //   }
    //   console.log('========')
    //   return params
    // }
  },
  created() {
    // 调用全局混合方法 第一个参数是请求地址对应的名称（api.js），第二个为参数
    this.getTreeList()
    this.getUnitList()
    this.isCompanyRole = this.roles.includes('company')
  },
  activated() {
    this.query()
  },
  methods: {
    getUnitList() {
      const vm = this
      vm.$cache.getDic('unit').then(res => {
        vm.unitList = res
        vm.query()
      })
    },
    // 下载
    downLoad() {
      const vm = this
      vm.$http
        .get('/products/import/template', { responseType: 'blob' })
        .then((res) => {
          downloadStream(res, '商品导入模板.xlsx')
        })
    },
    // 导入
    productImport() {
      const vm = this
      vm.importDialogVisible = true
    },
    // 搜索
    handleSearch() {
      const vm = this
      vm.queryParam.page = 1
      vm.query()
    },
    handleRefresh() {
      const vm = this
      vm.queryParam = {
        page: 1,
        limit: 10,
        type: '',
        value: '',
        is_disable: '',
        status: '',
        start_at: '', // 开始时间
        packing_method: '',
        operate_type: '',
        end_at: '',
        category_id: '',
        oversize: ''
      }
      vm.query()
    },
    handleChangeClassify(data) {
      this.queryParam.category_id = data[1] || ''
      this.handleSearch()
    },
    // 获取商品分类
    // getTreeList() {
    //   this.$http
    //     .get(`/getListTree`)
    //     .then((res) => {
    //       if (res.code === 10000 && res.data && res.data.length > 0) {
    //         res.data.forEach((element) => {
    //           element['label'] = element.name
    //           element['value'] = element.id
    //           if (element.children && element.children.length > 0) {
    //             element['disabled'] = false
    //             element.children.forEach((it) => {
    //               it['label'] = it.name
    //               it['value'] = it.id
    //             })
    //           } else {
    //             element['disabled'] = true
    //           }
    //         })
    //         this.classifyList = res.data
    //       }
    //     })
    //     .catch((err) => {
    //       console.log(err)
    //     })
    // },
    // 导出
    handleExport() {
      const vm = this
      vm.formVisibleDown = true
      // vm.exportLoading = true
      // const url = '/products/export'
      // const { type, value, is_disable, status, start_at, packing_method, operate_type, end_at, category_id } = vm.queryParam
      // const params = {
      //   is_disable,
      //   status,
      //   start_at, // 开始时间
      //   packing_method,
      //   operate_type,
      //   end_at,
      //   category_id
      // }
      // if (type) {
      //   params[type] = value
      // }
      // vm.$http.post(url, params).then(res => {
      //   downloadxlsx(res.data)
      //   vm.exportLoading = false
      // }).catch(() => {
      //   vm.exportLoading = false
      // })
    },
    addProductS() {
      this.$router.push('/product/productManage/addProductS')
    },
    addProductC() {
      this.$router.push('/product/productManage/addProductC')
    },
    // 新增-保存
    saveData() { },
    // 点击提交审核
    submitReview() {
      const dataLength = this.checkedList.length
      if (dataLength === 0) {
        this.$message.error('请至少选择一条数据')
        return false
      }
      const isEvery = this.checkedList.every((e) => {
        return e.status === 4 || e.status === 2
      })
      if (!isEvery) {
        this.$message.error('所选数据必须是待提交状态')
        return
      }
      this
        .$confirm(`确定提交审核吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          this.$http
            .post(`/product/batchExamine`, { ids: this.ids })
            .then((res) => {
              if (res.code === 10000) {
                this.$message.success('提交审核成功')
                this.query()
              }
            })
            .catch((err) => {
              console.log(err)
            })
        })
    },
    // 禁用
    stopClick() {
      const vm = this
      const dataLength = vm.checkedList.length
      if (dataLength === 0) {
        vm.$message.error('请至少选择一条数据')
        return false
      }

      vm.$confirm(`确定批量禁用吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        vm.$http
          .post(`/product/disable`, { ids: vm.ids })
          .then((res) => {
            if (res.code === 10000) {
              vm.$message.success('禁用成功')
              vm.query()
            }
          })
          .catch((err) => {
            console.log(err)
          })
      })
    },
    startClick() {
      const vm = this
      const dataLength = vm.checkedList.length
      if (dataLength === 0) {
        vm.$message.error('请至少选择一条数据')
        return false
      }

      vm.$confirm(`确定批量启用吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        vm.$http
          .post(`/product/enable`, { ids: vm.ids })
          .then((res) => {
            if (res.code === 10000) {
              vm.$message.success('启用成功')
              vm.query()
            }
          })
          .catch((err) => {
            console.log(err)
          })
      })
    },
    // 点击商品审核
    productReview() {
      const dataLength = this.checkedList.length
      if (dataLength === 0 || dataLength > 1) {
        this.$message.error('请至多选择一条数据')
        return false
      }
      const isEvery = this.checkedList.every((e) => {
        return e.status === 0
      })
      if (!isEvery) {
        this.$message.error('所选数据必须是待审核状态')
        return
      }
      this.$http
        .get(`/product/${this.ids[0]}`)
        .then((res) => {
          if (res.code === 10000) {
            // this.$message.success("提交审核成功");
            this.detailsData = res.data
          }
        })
        .catch((err) => {
          console.log(err)
        })
      this.dialogExamineVisible = true
      this.examineForm.status = 1
      this.examineForm.reason = ''
    },
    // 提交审核提交
    saveExamineData() {
      const vm = this
      vm.$refs.examineForm.validate(valid => {
        if (valid) {
          vm.$http
            .put(`/product/examine/${vm.ids[0]}`, vm.examineForm)
            .then((res) => {
              if (res.code === 10000) {
                vm.$message.success('提交商品审核成功')
                vm.query()
              }
            })
            .catch((err) => {
              console.log(err)
            })
          vm.dialogExamineVisible = false
        }
      })
    },
    // 自定义操作栏
    columnsHandler(cols) {
      const that = this
      return cols.concat({
        width: '200',
        label: '操作',
        align: 'center',
        fixed: 'left',
        propsHandler({ row }) {
          return {
            row: row,
            editAction: 'product@update',
            delAction: 'product@delete',
            buyerAction: 'product@updatePurchase'
          }
        },
        component: btnGroup,
        // listeners 可用于监听自定义组件内部 $emit 出的事件
        listeners: {
          updateBuyerClick(row) {
            that.orderId = row.id + ''
            that.buyersId = row.purchase_id + ''
            that.formVisible = true
          },
          editClick(row) {
            // console.log(row, 'row>>>>>')
            // 商品所属客户类型 0-内部员工 1-客户商品
            if (row.type === 1) {
              that.$router.push({
                path: '/product/productManage/addProductC',
                query: { id: row.id, title: '编辑商品-客户商品' }
              })
            } else if (row.type === 0) {
              that.$router.push({
                path: '/product/productManage/addProductS',
                query: { id: row.id, title: '编辑商品-内部商品' }
              })
            }
          },
          deleteClick(row) {
            that
              .$confirm('确认要删除？', '提示', {
                distinguishCancelAndClose: true,
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              })
              .then(() => {
                that.$http
                  .delete(`/product/${row.id}`)
                  .then((res) => {
                    if (res.code === 10000) {
                      that.$message.success('删除成功')
                      that.query()
                    }
                  })
                  .catch((err) => {
                    console.log(err)
                  })
              })
              .catch((action) => { })
          }
        }
      })
    },
    handleSizeChange(val) {
      const vm = this
      vm.queryParam.limit = val
      vm.query()
    },
    handleCurrentChange(val) {
      this.queryParam.page = val
      this.query()
    },
    query() {
      const vm = this
      let url = '/product'
      const arr = [
        'is_disable', // 禁启用
        'status', // 审核装填
        'start_at', // 开始时间
        'packing_method',
        'operate_type',
        'end_at' // 结束时间
      ]
      const { page, limit } = vm.queryParam
      url += `?page=${page}&limit=${limit}`
      arr.forEach(e => {
        url += `&${e}=${vm.queryParam[e]}`
      })
      this.formItems.forEach(e => {
        if (e.key !== 'category_ids') {
          url += `&${e.key}=${vm.queryParam[e.key] ?? ''}`
        }
      })
      if (vm.queryParam.category_ids && vm.queryParam.category_ids.length > 0) {
        const arr = vm.queryParam.category_ids
        url += `&category_id=${arr[arr.length - 1] ?? ''}`
      }
      //   if (type) {
      //     url += `&${type}=${value}`
      //   }
      vm.initTableData(url, null, (data) => {
        vm.data = data.map(e => {
          const item = vm.unitList.find(unit => `${unit.id}` === e.unit)
          e.unit = item ? item.dict_data_name : e.unit
          e.supplier_name = e.supplier_names || e.supplier_name
          return e
        })
      })
    },
    // 获取商品分类
    getTreeList() {
      const vm = this
      vm.$http.get(`/getListTree`).then(res => {
        const filter = (arr, parentIds = []) => {
          return arr.map(e => {
            e['value'] = e.id
            e['label'] = e.name
            // ids 用于 后续的 级联回填
            const ids = parentIds.concat()
            ids.push(e.id)
            e['ids'] = ids
            if (e.children) {
              e.children = filter(e.children, ids.concat())
            }
            return e
          })
        }
        const data = res.data.filter(e => e.children && e.children.length > 0)
        vm.classifyList = filter(data)
        vm.formItems = vm.formItems.map((arr) => {
          if (arr.key === 'category_ids') {
            arr.options = vm.classifyList
          }
          return arr
        })
        // vm.formItems[0].options = vm.classifyList
        vm.children = vm.classifyList.reduce((list, e) => {
          list = list.concat(e.children)
          return list
        }, [])
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.minheight-400 {
  height: 400px;
  overflow-y: auto;
}
</style>
